<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2017-12-29
 * @Time: 10:09
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： ImportCustomer.php
 */
namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\Db;
use think\Log;

/**
 * Class ImportCustomer
 * 客户名单导入
 * 命令：importCustomer 导入类型 [文件路径]
 *
 * @package app\admin\command
 */
class ImportCustomer extends Command {
    protected function configure()
    {
        // 导入方式：1=系统导入 2=文本导入 3=excel导入
        $this->addArgument('type', Argument::REQUIRED);

        // 导入文件
        $this->addArgument('file', Argument::OPTIONAL);

        $this->setName('importCustomer')->setDescription('客户名单导入');
    }

    protected function execute(Input $input, Output $output)
    {
        // 接收参数
        $args = $input->getArguments();

        switch ($args['type']) {
            case 1: // 将掌乾用户数据导入客户名单
                $usersData = Db::table('users')->alias('u')
                    ->join('users_extend_info uei', 'u.id=uei.user_id', 'left')
                    ->field('*,u.id as uid')
                    ->select();
                foreach ($usersData as $key=>$val) {
                    Db::startTrans();
                    try {
                        $data = [
                            'customer_mobile' => $val['mobile'],
                            'customer_realname' => $val['realname'],
                            'customer_sex' => $val['gender'],
                            'customer_address' => $val['user_address'],
                            'customer_qq' => $val['user_qq'],
                            'customer_wechat' => $val['user_wechat'],
                            'customer_userid' => $val['uid']
                        ];

                        $isCheck = Db::table('customer_list')->where('customer_mobile', $val['mobile'])->count();
                        if ($isCheck) {
                            Db::table('customer_list')->where('customer_mobile', $val['mobile'])->update($data);

                            echo "客户：{$val['mobile']} 已经存在，不再重复导入只作更新处理。".PHP_EOL;
                        } else {
                            $data['customer_addtime'] = time();
                            Db::table('customer_list')->insert($data);

                            echo "客户：{$val['mobile']} 导入成功！".PHP_EOL;
                        }

                        Db::commit();
                    } catch (\Exception $e) {
                        Log::error('客户导入失败：'.$e->getMessage());

                        echo "客户：{$val['mobile']} 导入失败！".PHP_EOL;

                        Db::rollback();
                    }
                }

                break;
            case 2: // 导入txt文本，每个手机号码一行
                if (!$args['file']) exit('请指定要导入的文本文件'.PHP_EOL);
                $file = $args['file'];
                if (file_exists($file)) {
                    $fp=fopen($file,'r');//以只读的方式打开文件
                    $i=0;
                    $list = [];
                    while(! feof($fp))
                    {
                        $list[$i]= fgets($fp);//fgets()函数从文件指针中读取一行
                        $i++;
                    }
                    fclose($fp);
                    $list=array_filter($list);
                    // print_r($list);
                    foreach ($list as $key=>$val) {
                        try {
                            $mobile = str_replace("\r\n","", $val);
                            $data = [
                                'customer_mobile' => $mobile
                            ];

                            $isCheck = Db::table('customer_list')->where('customer_mobile', $mobile)->count();
                            if ($isCheck) {
                                Db::table('customer_list')->where('customer_mobile', $mobile)->update($data);

                                echo "客户：{$mobile} 已经存在，不再重复导入只作更新处理。".PHP_EOL;
                            } else {
                                $data['customer_addtime'] = time();
                                Db::table('customer_list')->insert($data);

                                echo "客户：{$mobile} 导入成功！".PHP_EOL;
                            }

                            Db::commit();
                        } catch (\Exception $e) {
                            Log::error('客户导入失败：'.$e->getMessage());

                            echo "客户：{$mobile} 导入失败！".PHP_EOL;

                            Db::rollback();
                        }
                    }
                } else {
                    echo '文件不存在或路径不正确。请确认文件是否存在或输入完整路径后重新尝试操作！'.PHP_EOL;
                }

                break;
            case 3:
                exit('该功能暂未开放');
                if (!$args['file']) exit('请指定要导入的Excel文件'.PHP_EOL);
                break;
        }
    }
}